import React, { Key, useEffect, useState } from 'react';
import { ProCard, ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import { Button, Table, Popconfirm, Modal, message, Space } from 'antd';
import { connect, useDispatch } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import { createBrowserHistory } from 'history';

const history = createBrowserHistory();
export type TableListItem = {
  key: string;
  clusterLabel: string;
  id: string;
};
export type TableDetailItem = {
  key: string;
  phoneNumber: string;
  majorLabel: string;
  classLabel: string;
  stuName: string;
};

function ClusterList() {
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]); // 用于存储用户选择的行的keys
  const [isModalVisible, setIsModalVisible] = useState(false); // 控制对话框的可见性的状态变量
  const [clusterRowName, setClusterRowName] = useState<string>(''); //分群名
  const [tableListData, setTableListData] = useState<TableListItem[]>([]); //分群列表数据
  const [tableDetailData, setTableDetailData] = useState<TableDetailItem[]>([]); //分群详情数据
  const dispatch = useDispatch();

  const fetchClusterDetail = (clusterId: string) => {
    dispatch({
      type: 'Model_createclusterModel/getClusterDetailEffects',
      payload: {
        code: clusterId, // 将分群的ID传递给后端
        callback: (value: any) => {
          setTableDetailData(value);
        },
      },
    });
  };
  //对话框显现出来
  const showModal = () => {
    setIsModalVisible(true);
  };
  //隐藏对话框
  const handleCancel = () => {
    setIsModalVisible(false);
  };

  //查看详情
  const handleViewDetail = (record: TableListItem) => {
    setClusterRowName(record.clusterLabel); // 修正属性名为 clusterLabel
    showModal();
    // 获取所选分群的详细信息
    fetchClusterDetail(record.id);
  };
  //删除单个
  const handleDelete = (record: TableListItem) => {
    // console.log('Deleting:', record.id);
    dispatch({
      type: 'Model_createclusterModel/getClusterDeleteEffects',
      payload: {
        code: record.id, // 将分群的ID传递给后端
        callback: (value: any) => {
          // console.log(value);
          if (value.result === true) {
            message.success('删除成功！！！');
          } else {
            message.error('删除失败！！！');
          }
          window.location.reload();
        },
      },
    });
  };
  // // 处理删除所有已选项的函数
  // const handleDeleteSelected = () => {
  //   // 获取所有已选中行的数据
  //   const selectedRows = tableListData.filter((item) => selectedRowKeys.includes(item.key));
  //   //得到所选行的id组成的数组
  //   const selectedIds = selectedRows.map((row) => row.id);
  //   console.log('Selected IDs:', selectedIds);
  //   // 在这里执行删除已选项的逻辑
  // };

  //分群表格配置
  const Clustercolumns: ProColumns<TableListItem>[] = [
    {
      title: <b>分群名称</b>,
      width: 200,
      align: 'center',
      dataIndex: 'clusterLabel',
    },
    {
      title: <b>分群ID</b>,
      width: 200,
      align: 'center',
      dataIndex: 'id',
    },
    {
      title: <b>操作</b>,
      width: 200,
      align: 'center',
      render: (_, record) => (
        <div>
          <Button style={{ marginRight: '24px' }} type="primary" onClick={() => handleViewDetail(record)}>
            查看详情
          </Button>
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={() => handleDelete(record)}
            okText="确认"
            cancelText="取消"
          >
            <Button danger type="primary">删除分群</Button>
          </Popconfirm>
        </div>
      ),
    },
  ];
  //分群详情
  const Detailcolumns: ProColumns<TableDetailItem>[] = [
    {
      title: <b>名字</b>,
      width: 200,
      align: 'left',
      dataIndex: 'stuName',
    },
    {
      title: <b>学号</b>,
      width: 200,
      align: 'left',
      dataIndex: 'stuCode',
    },
    {
      title: <b>专业</b>,
      width: 200,
      align: 'left',
      dataIndex: 'majorLabel',
    },
    {
      title: <b>班级</b>,
      width: 200,
      dataIndex: 'classLabel',
    },
    {
      title: <b>电话号码</b>,
      width: 200,
      dataIndex: 'phoneNumber',
    },
  ];

  useEffect(() => {
    //获取数据接口
    dispatch({
      type: 'Model_createclusterModel/getClusterListEffects',
      payload: {
        // code: JSON.parse(props.user.currrentuser).account,
        code: 2022073,
        callback: (value: any) => {
          // console.log(value);
          setTableListData(value);
        },
      },
    });
  }, []);

  return (
    <PageContainer>
      <div style={{ display: 'flex' }}>
        <ProCard split="vertical" >
          <ProCard colSpan="100%" title="分群列表">
            <Space size="large" direction="vertical">
              <Space size="middle">
                <Button type="primary" onClick={() => { history.push("./onebyone"), window.location.reload() }}>新建个人分群</Button>
                <Button type="primary" onClick={() => { history.push("./ClusterByGroup"), window.location.reload() }}>新建分组分群</Button>
              </Space>
              <ProTable<TableListItem>
                columns={Clustercolumns}

                //配置表格的行选择功能。
                // rowSelection={{
                //   selectedRowKeys, // 设置用户选择的行
                //   onChange: (keys) => setSelectedRowKeys(keys), // 更新用户选择的行
                //   selections: [
                //     Table.SELECTION_ALL, //全选
                //     Table.SELECTION_INVERT, //反选
                //     Table.SELECTION_NONE, //全不选
                //   ],
                // }}
                style={{ width: 1400 }}
                dataSource={tableListData}
                options={false}
                search={false}
                pagination={{ pageSize: 10 }}
                rowKey="key"
              //headerTitle="分群列表"
              // toolBarRender={() => [
              //   <Popconfirm
              //     title="确定要删除吗？"
              //     onConfirm={handleDeleteSelected}
              //     okText="确认"
              //     cancelText="取消"
              //   >
              //     <Button key="deleteSelected" type="primary" danger>
              //       删除所有已选项
              //     </Button>
              //   </Popconfirm>,
              // ]}
              ></ProTable>
            </Space>
          </ProCard>
          <ProCard colSpan="60%">
            <Modal
              title={<b>{`"${clusterRowName}"分群成员：`}</b>}
              visible={isModalVisible}
              onCancel={handleCancel}
              footer={null} // 隐藏默认的底部按钮
              width={1200}
              style={{ marginRight: 130, marginTop: 120 }}
            >
              <ProTable<TableDetailItem>
                columns={Detailcolumns}
                dataSource={tableDetailData}
                options={false}
                search={false}
                pagination={{ pageSize: 10 }}
                rowKey="key"
              />
            </Modal>
          </ProCard>
        </ProCard>
      </div>
    </PageContainer >
  );
}

export default connect(({ Model_createclusterModel }: any) => ({
  Model_createclusterModel,
}))(ClusterList);
